package com.googlecode.jtoy.jdk6.hashcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashCodeMethodInvoked {

	public static void main(String[] args) {

		// AnObject array, array[0] = array[1]
		List<AnObject> list = new ArrayList<AnObject>();
		for (int i = 0; i < 4; i++) {
			if (i == 1) {
				list.add(new AnObject(0, "AnObject-0"));
			}
			list.add(new AnObject(i, "AnObject-" + i));
		}

		System.out.println("\ncompare 0 to others");
		for (int i = 1; i < 4; i++) {
			System.out.println("compare 0 to " + i);
			System.out.println(list.get(0).equals(list.get(i)));
		}

		Map<AnObject, AnObject> map = new HashMap<AnObject, AnObject>();
		System.out.println("\nput them to map...");
		for (int i = 0; i < 4; i++) {
			System.out.println("put " + i);
			map.put(list.get(i), list.get(i));
		}
		System.out.println("\nget from map...");
		for (int i = 0; i < 4; i++) {
			System.out.println("get " + i);
			map.get(list.get(i));
		}
	}
}

class AnObject {
	private int id;
	private String name;

	public AnObject(int id, String name) {
		this.id = id;
		this.name = name;
	}

	@Override
	public int hashCode() {
		System.out.println("hashCode method is invoked...");

		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		System.out.println("equals method is invoked...");

		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		AnObject other = (AnObject) obj;
		if (id != other.id)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
